var app = angular.module("app",[]);
app.config(function($httpProvider){
    $httpProvider.defaults.transformRequest=function(obj){
        var str=[];
        for(var p in obj){
            str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
        }
        return str.join("&");
    };
    $httpProvider.defaults.headers.post={
        'Content-Type':'application/x-www-form-urlencoded'
    }
})
var pays={};
document.addEventListener('plusready',function(){
	appElement=document.querySelector('[ng-controller=myCtrl]');
	$scope= angular.element(appElement).scope();
//	var uid = plus.storage.getItem('id');
//  $scope.initView(uid);
//	$scope.$apply();
//	
	// 获取支付通道
	plus.payment.getChannels(function(channels){
		for(var i in channels){
			var channel=channels[i];
			pays[channel.id]=channel;
//			console.log(JSON.stringify(channel));
			checkServices(channel);
		} 
	},function(e){
		outLine("获取支付通道失败："+e.message);
	});
});

var ws ,userid; 

var ordernum;
var price;
var ptype = 'wxpay'; 
var w=null;
var url = '';
//付款
function fukuan(orderid , price){
	plus.nativeUI.actionSheet( {cancel:"取消",buttons:[{title:"微信支付"},{title:"支付宝支付"},]}, function(e){
		var i=e.index;
		if(i==1){ 
//			console.log(orderid+","+price);  
			var type ="wxpay";
			payment(orderid ,price,type);  
		}else if(i==2){   
			var type ="alipay"
//			console.log(orderid+","+price); 
			payment(orderid ,price,type);  
		}
	});


        
}
function checkServices(pc){
	if(!pc.serviceReady){
		var txt=null;
		switch(pc.id){ 
			case "alipay":
			txt="检测到系统未安装“支付宝快捷支付服务”，无法完成支付操作，是否立即安装？";
			break;
			default:
			txt="系统未安装“"+pc.description+"”服务，无法完成支付，是否立即安装？";
			break;
		}
		plus.nativeUI.confirm(txt,function(e){
			if(e.index==0){
				pc.installService();
			}
		},pc.description);
	}
}

//支付
function payment(ordernum, price , ptype){
	//预设订单Id ——> 用户Id+当前时间戳
	orderid = ordernum+new Date().getTime();

	if(w){return;}//检查是否请求订单中
	
	if(ptype == 'alipay'){
//		console.log(webRoot + '/pay/Alipay.php?orderid=' + orderid + '&price='+price);
		url = webRoot + '?s=/App/Alipay/alipay';
		
	}else if(ptype == 'wxpay'){
//		console.log(webRoot + '/pay/index.php?orderid=' + orderid + '&price='+price);
		url = webRoot + '?s=/App/WXPay/wxPay';
	}
	w = plus.nativeUI.showWaiting('支付中...',{width:'80px',height:'80px',background:'rgba(0,0,0,0.3)'});
	// 请求支付订单
	var xhr=new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		switch (xhr.readyState) {
			case 4:
			w.close();  
			w = null;
			if (xhr.status == 200) { 
				var order = xhr.responseText;
//				console.log(pays[ptype]);
				order = $.parseJSON( order );
				console.log(order);
				plus.payment.request(pays[ptype], order.data.pay, function(result) { 
					console.log('支付成功');
				}, function(e) {
					console.log("提示", null, "支付失败");
					e = JSON.stringify(e);
					console.log(e);
				});
			} else { 
				plus.nativeUI.toast("获取订单信息失败！", null, "捐赠");
			}
			break;
		default:
			break;
		}
	}
	var postData = {
	    nmber: ordernum,
	    body: "测试",
	    money: price
    };
	postData = (function(obj){ // 转成post需要的字符串.
	    var str = "";
	 
	    for(var prop in obj){
	        str += prop + "=" + obj[prop] + "&"
	    }
	    return str;
	})(postData);
	postData=postData.substr(0, postData.length - 1);
//	console.log(url);
	xhr.open('post', url);
	xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
	xhr.send(postData);
}
